package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitors;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        visitors.setId(ObjectId.get());
        visitors.setDate(System.currentTimeMillis());
        mongoTemplate.save(visitors);
    }

    //根据时间查询
    public List<Visitors> topVisitors(Long userId, Long date) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("date").gt(date)
        );
        return queryScore(query);
    }

    //查询最近的几条记录
    public List<Visitors> topVisitors(Long userId, int num) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Order.desc("date"))).limit(num);

        return queryScore(query);
    }

    public List<Visitors> queryScore(Query query) {
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        for (Visitors visitor : visitors) {
            Query scoreQuery = new Query(
                    Criteria.where("userId").is(visitor.getUserId())
                            .and("toUserId").is(visitor.getVisitorUserId())
            );
            RecommendUser user = mongoTemplate.findOne(scoreQuery, RecommendUser.class);
            Double score = 60d;
            if(user != null) {
                score = user.getScore();
            }
            visitor.setScore(score);
        }
        return visitors;
    }
}
